<template>
  <div class="product-purchase">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商品购买</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入商品名称或编号"
              clearable
              @keyup.enter="handleSearch"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品列表 -->
      <div class="product-grid">
        <div 
          v-for="product in tableData" 
          :key="product.id" 
          class="product-card"
          v-loading="loading"
        >
          <div class="product-image">
            <el-image
              :src="getProductImage(product)"
              :alt="product.productName"
              fit="cover"
              :preview-src-list="[getProductImage(product)]"
              :initial-index="0"
              loading="lazy"
              @error="handleImageError"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                  <span>暂无图片</span>
                </div>
              </template>
            </el-image>
          </div>
          
          <div class="product-info">
            <h3 class="product-name" @click="viewProductDetail(product)">{{ product.productName }}</h3>
            <p class="product-code">编号：{{ product.productCode }}</p>
            
            <!-- 会员折扣信息 -->
            <div v-if="product.hasMemberDiscount" class="member-discount-section">
              <div class="member-badges">
                <el-tag 
                  :type="getMemberLevelType(product.userMemberLevel)" 
                  size="small"
                  class="member-tag"
                >
                  {{ product.memberLevelName }}
                </el-tag>
                <el-tag type="danger" size="small" class="discount-tag">
                  {{ product.discountDescription }}
                </el-tag>
              </div>
              
              <div class="price-display">
                <span class="original-price">¥{{ product.sellingPrice }}</span>
                <span class="discount-price">¥{{ product.memberDiscountPrice }}</span>
              </div>
              
              <div class="saved-amount">
                立省 ¥{{ product.savedAmount }}
              </div>
            </div>
            
            <!-- 普通用户价格 -->
            <div v-else class="normal-price-section">
              <div class="member-badges">
                <el-tag type="info" size="small" class="member-tag">
                  {{ product.memberLevelName || '普通用户' }}
                </el-tag>
              </div>
              <div class="product-price">
                <span class="price">¥{{ product.sellingPrice }}</span>
              </div>
            </div>
            
            <div class="stock-info">
              <el-tag 
                :type="product.currentStock > 0 ? 'success' : 'danger'" 
                size="small"
              >
                库存：{{ product.currentStock }}
              </el-tag>
            </div>
            
            <div class="product-actions">
              <el-button
                type="text"
                size="small"
                @click="viewProductDetail(product)"
              >
                查看详情
              </el-button>
              <el-button
                type="primary"
                size="small"
                :disabled="product.currentStock <= 0"
                @click="showPurchaseDialog(product)"
              >
                立即购买
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!loading && tableData.length === 0" description="暂无商品数据" />

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[12, 24, 48, 96]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 购买对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="购买商品"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品图片">
          <el-image
            :src="getProductImage(selectedProduct)"
            :alt="selectedProduct.productName"
            style="width: 80px; height: 80px"
            fit="cover"
            loading="lazy"
          >
            <template #error>
              <div class="image-slot-small">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="selectedProduct.productName" disabled />
        </el-form-item>
        <el-form-item label="商品编号">
          <el-input v-model="selectedProduct.productCode" disabled />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="selectedProduct.sellingPrice" disabled>
            <template #prepend>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="可用库存">
          <el-input v-model="selectedProduct.currentStock" disabled />
        </el-form-item>
        <el-form-item label="购买数量" prop="purchaseQuantity">
          <el-input-number
            v-model="form.purchaseQuantity"
            :min="1"
            :max="selectedProduct.currentStock"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="总金额">
          <el-input :value="totalAmount" disabled>
            <template #prepend>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePurchase" :loading="purchasing">
            确认购买
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="商品详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="product-detail" v-if="selectedProduct">
        <div class="detail-image">
          <el-image
            :src="getProductImage(selectedProduct)"
            :alt="selectedProduct.productName"
            fit="cover"
            loading="lazy"
          >
            <template #error>
              <div class="image-slot-large">
                <el-icon><Picture /></el-icon>
                <span>暂无图片</span>
              </div>
            </template>
          </el-image>
        </div>
        
        <div class="detail-info">
          <h2>{{ selectedProduct.productName }}</h2>
          <div class="detail-row">
            <span class="label">商品编号：</span>
            <span>{{ selectedProduct.productCode }}</span>
          </div>
          <div class="detail-row">
            <span class="label">型号：</span>
            <span>{{ selectedProduct.model || '暂无' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">销售价格：</span>
            <span class="price-large">¥{{ selectedProduct.sellingPrice }}</span>
          </div>
          <div class="detail-row">
            <span class="label">当前库存：</span>
            <el-tag 
              :type="selectedProduct.currentStock > 0 ? 'success' : 'danger'"
              size="large"
            >
              {{ selectedProduct.currentStock }} 件
            </el-tag>
          </div>
          <div class="detail-row">
            <span class="label">供应商：</span>
            <span>{{ selectedProduct.supplierName || '暂无' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">分类：</span>
            <span>{{ selectedProduct.categoryName || '暂无' }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            :disabled="selectedProduct.currentStock <= 0"
            @click="showPurchaseFromDetail"
          >
            立即购买
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Picture } from '@element-plus/icons-vue'
import { getOnlineProducts } from '@/api/storeProduct'
import { purchaseProduct } from '@/api/purchase'
import { useRouter } from 'vue-router'
import defaultProductImage from '@/assets/default-product.svg'

// 响应式数据
const loading = ref(false)
const purchasing = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const formRef = ref()
const router = useRouter()

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 12,
  total: 0
})

// 选中的商品
const selectedProduct = ref({})

// 购买表单
const form = reactive({
  productId: null,
  purchaseQuantity: 1,
  remark: ''
})

// 表单验证规则
const rules = {
  purchaseQuantity: [
    { required: true, message: '请输入购买数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '购买数量必须大于0', trigger: 'blur' }
  ]
}

// 计算总金额
const totalAmount = computed(() => {
  if (selectedProduct.value.sellingPrice && form.purchaseQuantity) {
    return (selectedProduct.value.sellingPrice * form.purchaseQuantity).toFixed(2)
  }
  return '0.00'
})

// 获取会员等级标签类型
const getMemberLevelType = (level) => {
  switch (level) {
    case 'VIP1':
      return 'danger'
    case 'VIP2':
      return 'success'
    case 'VIP3':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取商品图片URL
const getProductImage = (product) => {
  const imageUrl = product?.image || defaultProductImage
  console.log(`商品 ${product?.productName} 的图片URL:`, imageUrl)
  console.log('商品完整数据:', product)
  return imageUrl
}

// 获取商品列表数据
const getTableData = async () => {
  try {
    loading.value = true
    const response = await getOnlineProducts(
      null, // 不再传递店长ID，获取所有店长的商品
      pagination.current,
      pagination.size,
      searchForm.keyword
    )
    
    if (response.code === 200) {
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
      
      // 调试信息：检查商品数据
      console.log('获取到的商品数据:', tableData.value)
      tableData.value.forEach(product => {
        console.log(`商品: ${product.productName}, 图片URL: ${product.image}`)
      })
    } else {
      ElMessage.error(response.message || '获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  pagination.current = 1
  getTableData()
}

// 页面大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getTableData()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getTableData()
}

// 查看商品详情
const viewProductDetail = (product) => {
  // 使用编程式导航跳转到商品详情页面
  router.push({
    name: 'ProductDetail',
    params: { id: product.id }
  })
}

// 从详情页面购买
const showPurchaseFromDetail = () => {
  detailDialogVisible.value = false
  showPurchaseDialog(selectedProduct.value)
}

// 显示购买对话框
const showPurchaseDialog = (product) => {
  selectedProduct.value = { ...product }
  form.productId = product.id
  form.purchaseQuantity = 1
  form.remark = ''
  dialogVisible.value = true
}

// 处理购买
const handlePurchase = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 确认购买
    await ElMessageBox.confirm(
      `确认购买 ${selectedProduct.value.productName} ${form.purchaseQuantity} 件，总金额 ¥${totalAmount.value}？`,
      '确认购买',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    purchasing.value = true
    
    const purchaseData = {
      productId: form.productId,
      purchaseQuantity: form.purchaseQuantity,
      remark: form.remark
    }
    
    const response = await purchaseProduct(purchaseData)
    
    if (response.code === 200) {
      ElMessage.success('购买成功')
      dialogVisible.value = false
      getTableData() // 刷新商品列表
    } else {
      ElMessage.error(response.message || '购买失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('购买失败:', error)
      ElMessage.error('购买失败')
    }
  } finally {
    purchasing.value = false
  }
}

// 处理图片加载错误
const handleImageError = () => {
  console.log('图片加载失败')
}

// 页面加载时获取数据
onMounted(() => {
  getTableData()
})

// 测试API
const testAPI = async () => {
  try {
    console.log('开始测试API...')
    const response = await getOnlineProducts(null, 1, 5, '')
    console.log('API响应:', response)
    console.log('响应数据:', response.data)
    if (response.data && response.data.records) {
      console.log('商品列表:', response.data.records)
      response.data.records.forEach((product, index) => {
        console.log(`商品${index + 1}:`, {
          id: product.id,
          name: product.productName,
          image: product.image,
          price: product.sellingPrice
        })
      })
    }
  } catch (error) {
    console.error('API测试失败:', error)
  }
}
</script>

<style scoped>
.product-purchase {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.product-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  background: #fff;
}

.product-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.product-image {
  height: 200px;
  overflow: hidden;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.image-slot-small {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  background: #f5f7fa;
  color: #909399;
}

.image-slot-large {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 300px;
  background: #f5f7fa;
  color: #909399;
}

.product-info {
  padding: 15px;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
  cursor: pointer;
  transition: color 0.3s;
}

.product-name:hover {
  color: #409eff;
}

.product-code {
  font-size: 12px;
  color: #909399;
  margin: 0 0 10px 0;
}

/* 会员折扣样式 */
.member-discount-section {
  margin-bottom: 15px;
}

.member-badges {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.member-tag {
  font-weight: 600;
}

.discount-tag {
  font-weight: 600;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.price-display {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.original-price {
  font-size: 14px;
  color: #909399;
  text-decoration: line-through;
}

.discount-price {
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.saved-amount {
  font-size: 12px;
  color: #67c23a;
  font-weight: 600;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #67c23a;
  display: inline-block;
}

/* 普通用户价格样式 */
.normal-price-section {
  margin-bottom: 15px;
}

.normal-price-section .member-badges {
  margin-bottom: 10px;
}

.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.price {
  font-size: 18px;
  font-weight: 600;
  color: #e6a23c;
}

.stock-info {
  margin-bottom: 15px;
}

.product-actions {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.product-actions .el-button {
  flex: 1;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.product-detail {
  display: flex;
  gap: 20px;
}

.detail-image {
  flex: 0 0 300px;
  height: 300px;
}

.detail-image .el-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.detail-info {
  flex: 1;
}

.detail-info h2 {
  margin: 0 0 20px 0;
  color: #303133;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.detail-row .label {
  flex: 0 0 100px;
  font-weight: 600;
  color: #606266;
}

.price-large {
  font-size: 24px;
  font-weight: 600;
  color: #e6a23c;
}

@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 15px;
  }
  
  .product-detail {
    flex-direction: column;
  }
  
  .detail-image {
    flex: none;
    height: 250px;
  }
}
</style> 